﻿using System;
using System.Collections.Generic;
using System.IO;

namespace Nutilities.Net.Binary
{
    public class Broadcaster<T> : BinaryWriter
        where T : IThreadedConnection
    {
        public List<T> Clients { get; set; }

        public Broadcaster(List<T> clients)
            : base(new MemoryStream())
        {
            Clients = clients;
        }

        public virtual void FlushTo(List<T> clients)
        {
            MemoryStream ms = (MemoryStream)OutStream;
            byte[] bytes = ms.ToArray();

            lock (clients)
            {
                for (int i = clients.Count - 1; i >= 0; i--)
                {
                    T client = clients[i];
                    if (client.Socket.Connected)
                    {
                        try
                        {
                            client.Writer.Write(bytes);
                            client.Writer.Flush();
                        }
                        catch (ObjectDisposedException)
                        {
                            Console.WriteLine("ObjectDisposedException");
                            client.OnDisconnected();
                        }
                    }
                }
            }

            OutStream = new MemoryStream();
        }

        public override void Flush()
        {
            FlushTo(Clients);
        }
    }
}
